package com.eshop.common.condition;


import com.eshop.utils.StringUtils;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPathCheckCondition implements Condition {
    private RestTemplate restTemplate;
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String httpPath = conditionContext.getEnvironment().getProperty("file.httpPath");
        if(StringUtils.isBlank(httpPath)) return false;
        return getInputStream();
    }

    //判断是否能连接成功
    public static boolean getInputStream() {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL("http://110.40.176.175:91/static/api/file/pic/20210706113002899088.jpg");
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode != 200) {
                return false;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
